package com.bright.hander;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

//拦截有@Controller的类
@ControllerAdvice
public class ControllerExceptionHander {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


//    标识这个方法是可以做异常处理的
    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHander(HttpServletRequest request,Exception e) throws Exception {
        logger.error("URL:{},Exception :{}",request.getRequestURL(),e);


//        加一个判断资源是否找得到
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
            throw  e;
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("URL",request.getRequestURL());
        mv.addObject("msg",e);
        mv.setViewName("error/error");

        return mv;
    }
}
